<?php

namespace process;

use Workerman\Connection\TcpConnection;

/***
 * 开启一个websocket
 * 监听端口定义在config目录下的process.php中的Websocket配置
 * @package process
 */
class Websocket
{
    public function onConnect(TcpConnection $connection)
    {
    }

    public function onWebSocketConnect(TcpConnection $connection, $http_buffer)
    {
    }

    public function onMessage(TcpConnection $connection, $data): void
    {
        // 客户端发送心跳，格式定义为数组code=1001
        $data = json_decode($data, true);
        if ($data['code'] == 1001) {
            $connection->send(json_encode(['code' => 1001, 'msg' => 'heartbeat']));
        }
        // 其他业务可以跟前端协商，定义数组code=1002开始
    }

    public function onClose(TcpConnection $connection): void
    {
        // 关闭websocket
        $connection->close();
    }
}